<template>
	<view>
		<!-- <view>{{$store.state.person.name}}</view> -->
		<!-- <view class="pois_f_t bjys_b">
			<title @click="customEvent" :list="tabs"></title>
		</view> -->
		<map :enable-3D="true" :enable-overlooking="true" :enable-indoorMap="true" :enable-building="true"
			:enable-poi="true" :enable-traffic="true" :enable-satellite="false" show-location class="map"
			:polyline="polyline" id="map" :latitude="latitude" :longitude="longitude" :scale="scale" :markers="markers"
			layer-style="2" @markertap="markertap" @tap="tap" style="height:75vh;width: 100%;">
			<!-- 自定义气泡 -->
			<cover-view slot="callout">
				<cover-view class="callout">
					<cover-view class="clr " v-show="item.title!=''" v-for="(item,index) in markers" :key="index"
						:marker-id="item.id">
						<cover-view class="bjys_b customCallout border_r">
							<cover-view class="flex clr_hie blok widht">
								<cover-view class="font_size_22">￥</cover-view>
								<cover-view class="font_size_28 widht">52</cover-view>
							</cover-view>
							<cover-view class="bjys_lv_1 flex border_r marg_top_10">
								<cover-view
									class="bjys_lv padd_top_7 padd_bottom_7 padd_zy_10 border_r clr blok font_size_24">快</cover-view>
								<cover-view class="font_size_24 clr_lv marg_left_10 marg_right_10">22222</cover-view>
							</cover-view>
						</cover-view>
						<cover-image style="width: 30rpx; height: 30rpx;  margin: -10rpx auto;"
							src="/static/jt.png"></cover-image>
					</cover-view>
				</cover-view>
			</cover-view>
		</map>
		<cover-image @click="obtainLandmarks" class="btn" style="width: 60rpx; height: 60rpx;" src="/static/dw.png"
			mode=""></cover-image>
		<cover-image @click="goPaht" class="three" style="width: 60rpx; height: 60rpx;" src="/static/dw.png"
			mode=""></cover-image>
		<!-- 抽屉 -->
		<view @touchend="handleTouchEnd" class="pois_f transition box_hei bjys_b" :style="{ height: boxHeight + 'px' }">
			<view class="bjys_hui border_r marg_top_20" style="height: 10rpx; width: 100rpx; margin: 0 auto;">
			</view>
			<view class="bjys_hui clr_h  padd_20 marg border_r" @click="getBoardingPosition(1)">
				{{strAddress?strAddress:'请选择上车位置'}}
			</view>
			<view class="bjys_hui clr_h padd_20 marg border_r" @click="getBoardingPosition(2)">
				{{endAddress?endAddress:'请选择下车位置'}}
			</view>
			<view @click="plan" class="marg_zy marg_top_50 bjys_lv text_center clr padd_20 border_r">确认</view>
			<!-- 路线进度 -->

			<view class="padd_20 marg">
				<scroll-view :scroll-top="scrollTop" scroll-y="true" style="height: 400rpx;" @scrolltoupper="upper"
					@scrolltolower="lower" @scroll="scroll">
					<up-steps :current="current" direction="column">
						<view v-for="(item,index) in steps" :key="index">
							<up-steps-item :title="item.instruction" :desc="item.road_name"></up-steps-item>
						</view>
					</up-steps>
				</scroll-view>
			</view>

		</view>
	</view>
</template>

<script setup lang="ts">
	// import { init } from '@/api/api.js'
	import { useStore } from 'vuex'
	import { routePlanning } from '@/utils/map_sdk.js'
	import { ref, onMounted, onBeforeMount, onUpdated, onBeforeUnmount, computed, onUnmounted, toRefs, watch } from 'vue';
	// 变量
	const isIndex = ref(0)
	const tabs = ref([{
		name: '栋哥'
	}, {
		name: '小杨哥'
	}, {
		name: '小廖'
	}, {
		name: '小黎'
	}, {
		name: '陈总'
	}])
	const longitude = ref(null)//经度
	const latitude = ref(null)//维度
	const markers = ref([])//标记点
	const mapCtx = ref(null)//地图实例
	const boxHeight = ref(200)//控制高度
	const strAddress = ref('')//开始位置
	const endAddress = ref('')//结束位置
	const form = ref({})//起金纬度
	const current = ref(0)//当前走到的位置索引

	const to = ref({})//始金纬度
	const polyline = ref([{//路线
		points: [],
		color: "#00d3ff",
		width: 8,
		arrowLine: true,
		borderColor: '#097cc1',
		// colorList: ['#00d3ff']
	}])
	const steps = ref([])///具体方案，按交通工具的换乘分段

	// vuex
	const { state, commit } = useStore();    //获取store对象
	const count = computed(() => state.person.name);
	const person = toRefs(state)
	console.log(count.value, 'count')
	console.log(person, 'person')
	commit('TOKEN', '6666666666666666666666666')

	// 监听属性
	watch(isIndex, (newValue, oldValue) => {
		// console.log(newValue, oldValue, isIndex.value)
	})
	// 点击事件
	const customEvent = (index : number) => {
		console.log(index)
		if (index == 2) {
			uni.navigateTo({
				url: '/pages/map/map'
			})
		}
		isIndex.value = index
	}
	// 周期方法
	onMounted(() => {
		mapCtx.value = uni.createMapContext('map', this);
		// getList()
		setTimeout(() => {
			getList()
			// clearInterval()
		}, 2000)
	});

	// 跳转3d
	const goPaht = () => {
		uni.navigateTo({
			url: '/pages/three/three'
		})
	}

	// 选择坐标地址
	const obtainLandmarks = () => {
		uni.navigateTo({
			url: '/pages/map/map'
		})
	}
	//控制探出窗高度
	const handleTouchEnd = (e) => {
		// console.log(e.changedTouches[0].screenY)
		if (e.changedTouches[0].screenY < 700) {
			// console.log('小于800');
			boxHeight.value = 400
		} else if (e.changedTouches[0].screenY > 700) {
			boxHeight.value = 200
		}
		// 在这里执行“松开”时的逻辑
	}
	// 选择上车位置
	const getBoardingPosition = (type) => {
		uni.chooseLocation({
			success: function (res) {
				if (type == 1) {
					strAddress.value = res.address
					form.value = {
						latitude: res.latitude,
						longitude: res.longitude
					}
				} else {
					endAddress.value = res.address
					to.value = {
						latitude: res.latitude,
						longitude: res.longitude
					}
				}
			}
		});
	}
	//规划路线
	const plan = () => {
		if (!strAddress.value) return ''
		if (!endAddress.value) return ''
		// return console.log(polyline.value[0].points, 'lll')
		routePlanning(form.value, to.value).then(res => {
			if (res.code == 1) {
				console.log(res, 'res')
				polyline.value[0].points = res.polyline
				steps.value = res.steps
				steps.value.forEach(k => {
					// 计算两点之间的距离（这里简化处理，不进行精确的距离计算）此处为计算下一个点的模糊位置
					const isWithinRange = isApproximatelyEqual(latitude.value, k.position.latitude) && isApproximatelyEqual(longitude.value, k.position.longitude);

					function isApproximatelyEqual(num1, num2) {
						// 定义一个误差范围，比如0.001表示经度或纬度差异在1米以内算等
						const threshold = 1;
						return Math.abs(num1 - num2) < threshold;
					}
					// 根据isWithinRange的值进行相应操作
					if (isWithinRange) {
						console.log('当前位置与目标位置差不多');
						current.value++
					} else {
						console.log('当前位置与目标位置不等');
					}
				})


				mapCtx.value.includePoints({//此处为显示路线在地图中间
					points: res.polyline,
					padding: [60, 60, 60, 60]
				})
				// 起始标记点图标
				markers.value.push({
					id: -1,
					title: '',
					latitude: polyline.value[0].points[0].latitude,
					longitude: polyline.value[0].points[0].longitude,
					width: 30,
					height: 30,
					iconPath: '/static/q.png',
					customCallout: {
						anchorX: 0,
						anchorY: 15,
						display: "ALWAYS"
					},
				}, {
					id: -2,
					title: '',
					latitude: polyline.value[0].points[polyline.value[0].points.length - 1].latitude,
					longitude: polyline.value[0].points[polyline.value[0].points.length - 1].longitude,
					width: 30,
					height: 30,
					iconPath: '/static/z.png',
					customCallout: {
						anchorX: 0,
						anchorY: 15,
						display: "ALWAYS"
					},
				})

				boxHeight.value = 400//将盒子高度提升最高
			}
		})
	}
	// 获取当前金纬度
	const getList = () => {
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				longitude.value = res.longitude
				latitude.value = res.latitude
				console.log(66)
				mapCtx.value.moveToLocation({
					latitude: res.latitude,
					longitude: res.longitude,
				})
				// getlongitude()
			},
			fail: (err) => {
				console.error('获取位置失败：', err);
			}
		});

	}
	const getlongitude = () => {
		init({
			page: 1,
			pagesize: 999,
			location: `${longitude.value},${latitude.value}`,
		}).then(res => {
			console.log(res, 'kkkkkkkkk')
			if (res.code == 200) {
				// 此处是防止筛选之后地图未更新
				markers.value = []
				// that.markers = res.data.list
				res.rows.forEach((item, index) => {
					const localInfo = {
						id: Number(item.id),
						title: item.name,
						address: item.address,
						price: item.price,
						fast: item.deviceMap.fast[0],
						fast1: item.deviceMap.fast[1],
						latitude: item.lat,
						longitude: item.lng,
						joinCluster: true,
						width: 50,
						height: 55,
						iconPath: '/static/j.png',
						customCallout: {
							anchorX: 0,
							anchorY: 15,
							display: "ALWAYS"
						},
					}
					markers.value.push(localInfo)
					openAggator()
				})
			} else {
			}
		})
	}
	const openAggator = () => {
		mapCtx.value.initMarkerCluster({
			enableDefaultStyle: false,
			zoomOnClick: true,
			gridSize: 60,
			complete: (res) => {
				console.log('initMarkerCluster', res)
			}
		})
		mapCtx.value.on('markerClusterCreate', res => {
			const clusters = ref(res.clusters)
			const markers = clusters.value.map(cluster => {
				const {
					center,
					clusterId,
					markerIds
				} = cluster
				return {
					...center,
					width: 0,
					height: 0,
					clusterId, // 必须
					label: {
						content: markerIds.length + '',
						fontSize: 16,
						width: 50,
						color: '#ffffff',
						height: 50,
						bgColor: '#8dc322',
						borderRadius: 25,
						textAlign: 'center',
						anchorX: 0,
						anchorY: -80,
					},
				}
			})
			console.log('markers', markers)
			mapCtx.value.addMarkers({
				markers,
				clear: false,
				complete(res) {
				}
			})
		})
	}

	onBeforeMount(() => {
		console.log("触发onBeforeMount钩子");
	});

	onUpdated(() => {
		console.log("触发Updated钩子");
	});

	onBeforeUnmount(() => {
		console.log("触发BeforeUnmount钩子");
	});

	onUnmounted(() => {
		console.log("触发Unmounted钩子");
	});
</script>

<style scoped lang="scss">
	.customCallout {
		box-sizing: border-box;
		padding: 10rpx 15rpx;
		box-shadow: 0 0 10rpx rgba(0, 0, 0, .3);
	}

	.btn {
		position: fixed;
		top: 6%;
		left: 8%;
		z-index: 9999;
	}

	.three {
		position: fixed;
		top: 13%;
		left: 4%;
		z-index: 9999;
	}
</style>